import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Modal, Grid, Input, InputNumber, Card } from '@arco-design/web-react';
import styles from './style/index.module.less';
import * as Model from '@/services/model';
import * as Constants from './constants';
import { RangeEditorModal } from './rangeEditorModal';
import { Time } from '@/utils';
const { Row, Col } = Grid;
interface DetailModalProps {
  workPeriod?: Model.WorkPeriod.default | false;
  onCancel: () => void;
  onOk: (params: Model.Truck) => void;
}

const rowHeight = 36;

export const DetailModal = (props: DetailModalProps) => {
  const [detailData, setDetailData] =
    useState<{ times: Partial<Model.WorkPeriod.TimeRange>[] }[]>();
  const [timeDetail, setTimeDetail] = useState<
    Partial<Model.WorkPeriod.TimeRange> | false
  >(false);
  const [selectedTimes, setSelectedTimes] = useState([]);

  const dealWithTimes = (period: Model.WorkPeriod.default) => {
    const res = Constants.weekDays.map((w) => {
      return {
        weekday: w,
        times: period.timeRanges.filter((e) => e.weekday === w),
      };
    });
    return res;
  };
  useEffect(() => {
    document.body.style.setProperty('--workPeriod-row-size', `${rowHeight}px`);
  }, []);

  useEffect(() => {
    if (props.workPeriod !== false) {
      setDetailData(dealWithTimes(props.workPeriod));
    }
  }, [props.workPeriod]);

  const submit = async () => {
    props.onOk(detailData as any);
  };

  /**
   * @name: 处理选中事件
   * @param:  t 选中单元格数据 w 选中周数据
   */

  const handleEvent = (t, w) => {
    return {
      onMouseDown: () => {
        setSelectedTimes([
          {
            weekday: w,
            ...t,
          },
        ]);
      },

      onMouseEnter: () => {
        if (
          selectedTimes?.length > 0 &&
          selectedTimes.some((e) => e.weekday === w && e.start !== t.start)
        ) {
          setSelectedTimes([
            selectedTimes[0],
            {
              weekday: w,
              ...t,
            },
          ]);
        }
      },
    };
  };

  const handleMouseUp = () => {
    if (selectedTimes?.length > 0) {
      const _selectedTimes = [
        ...selectedTimes.sort((e1, e2) => e1.start - e2.start),
      ];
      setTimeDetail({
        weekday: _selectedTimes[0].weekday,
        start: Time.timeToString([_selectedTimes[0].start]),
        end: Time.timeToString([_selectedTimes[_selectedTimes.length - 1].end]),
      });
      setSelectedTimes([]);
    }
  };

  return (
    <Modal
      visible={props.workPeriod !== false}
      title={`${props.workPeriod && props.workPeriod.id ? '修改' : '新增'}日程`}
      mountOnEnter
      unmountOnExit
      onCancel={props.onCancel}
      onOk={submit}
      alignCenter={true}
      okText="提交"
      cancelText="取消"
      style={{ width: 800 }}
    >
      <div className={styles.timeTable} onMouseUp={handleMouseUp}>
        <div className={styles.table}>
          {['', ...Constants.weekDays].map((e) => {
            const dayRender = () => {
              if (!e) {
                return (
                  <div className={styles.day}>
                    {Constants.timeRanges.map((f) => {
                      return (
                        <div key={f.name} className={styles.line}>
                          {f.start.toString().padStart(2, '0')}:00
                        </div>
                      );
                    })}
                  </div>
                );
              } else {
                return (
                  <div className={styles.day}>
                    {Constants.timeRanges.map((f, k) => {
                      const _times =
                        detailData?.[
                          Constants.weekDays.indexOf(e)
                        ]?.times?.filter((t) => {
                          const [startHour] = Time.stringToTime(t.start);
                          return (
                            startHour >= f.start && startHour < f.start + 1
                          );
                        }) || [];

                      // 判断是否在选择范围里
                      const isInSelectedRange = () => {
                        if (selectedTimes?.[0]?.weekday !== e) {
                          return false;
                        }
                        if (
                          selectedTimes.some((t) => {
                            return t.start === f.start;
                          })
                        ) {
                          return true;
                        }
                        const _selectedTimes = [...selectedTimes].sort(
                          (e1, e2) => e1.start - e2.start
                        );
                        if (
                          _selectedTimes?.[0]?.start < f.start &&
                          _selectedTimes?.[1]?.start > f.start
                        ) {
                          return true;
                        }
                        return false;
                      };

                      return (
                        <div
                          key={f.name}
                          className={[
                            styles.line,
                            isInSelectedRange() && styles.selected,
                          ].join(' ')}
                          {...handleEvent(f, e)}
                        >
                          {_times.map((g) => {
                            const [startHour, startMinute] = Time.stringToTime(
                              g.start
                            );
                            const [endHour, endMinute] = Time.stringToTime(
                              g.end
                            );
                            const top = (rowHeight * startMinute) / 60;
                            const height =
                              (rowHeight *
                                ((endHour - startHour) * 60 +
                                  endMinute -
                                  startMinute)) /
                              60;
                            return (
                              <div
                                key={g.start + g.end}
                                className={styles.timeRange}
                                style={{ top: top, height: height }}
                                onClick={(event) => {
                                  event.stopPropagation();
                                  setTimeDetail(g);
                                }}
                              ></div>
                            );
                          })}
                        </div>
                      );
                    })}
                  </div>
                );
              }
            };

            return (
              <div className={styles.row} key={e}>
                <div className={styles.th}>
                  <span>{e}</span>
                </div>
                {dayRender()}
              </div>
            );
          })}
        </div>
      </div>
      <RangeEditorModal
        time={timeDetail}
        onCancel={() => setTimeDetail(false)}
        onOk={(params) => {
          detailData?.[
            Constants.weekDays.findIndex((e) => e === params.weekday)
          ]?.times?.push(params);
          setDetailData([].concat(detailData));
          setTimeDetail(false);
        }}
      />
    </Modal>
  );
};
